//
//  MTClubDetailViewController.swift
//  MT
//
//  Created by ooops on 2019/12/28.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import Eureka
import MTCategory
import RxSwift
import RxCocoa

import Kingfisher
import YPNavigationBarTransition

class MTClubDetailViewController: BaseFormViewController {
    
    public var group: JMSGGroup!
    fileprivate lazy var users: [JMSGUser] = []
    private var isEditMode: Bool = false
    private let provider: MTProvider = MTProvider<MTClubApi>()
    
    typealias updateClubInfoUserClosure = () -> Swift.Void
    
    private var completeClosure: updateClubInfoUserClosure?
    
    /// 是否是从聊天界面过来的
    var comformChat: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        /// 群主可以修改细信息
        if group.owner == JMSGUser.myInfo().username {
            navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightEditButton)
            //self.commitButton.isHidden = false
        }
        
        title = "俱乐部详情"
        tableView.backgroundColor = UIColor.theme.background
        tableView.separatorStyle = .none
        tableView.contentInset = UIEdgeInsets(top: 40, left: 0, bottom: 0, right: 0)
        tableView.contentInsetAdjustmentBehavior = .always
        setupForm(hiddenGid: false)
        view.addSubview(commitButton)
        
        commitButton.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-20)
            make.width.equalTo(210)
            make.height.equalTo(44)
        }
        
        /// 解析数据
        parseData()
        
        let isOwner = self.group.owner == JMSGUser.myInfo().username
        /// 是俱乐部成员 / 俱乐部管理员, 可看见活动按钮
        if isOwner || self.group.memberInfo(withUsername: JMSGUser.myInfo().username, appkey: nil) != nil {
            self.view.addSubview(IMBtn)
            IMBtn.snp.makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.bottom.equalToSuperview().offset(-20)
                make.width.equalTo(210)
                make.height.equalTo(44)
            }
        }
    }
    
    convenience init(group: JMSGGroup, updateClubClosure: updateClubInfoUserClosure?) {
        self.init()
        self.group = group
        self.completeClosure = updateClubClosure
        users = group.memberArray()
        //self.tableView.reloadData()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.completeClosure?()
    }
    
    //operateClubUserupdateClubClosure
    
    /// ["pushId" : "", "type" : "", "users" : {"", ""}]
    
    // MARK: - 创建俱乐部活动
    @objc private func commitClubInfo() {
        let validationErrors: [ValidationError] = self.form.validate()
        if validationErrors.count != 0 {
            self.showValidationMsg(msgs: validationErrors)
            return
        }
        
        let values = self.form.values()
    
        var requestParam: [String : Any] = [
            "area": "",
            "city": "",
            "pushId": self.group.gid,
            "name": "",
            "province": "",
            "remark": ""
        ]
        
        if let remark = values[clubDescriptionKey] as? String {
            requestParam.updateValue(remark, forKey: "remark")
        }
        
        if let name = values[clubNameKey] as? String {
            requestParam.updateValue(name, forKey: "name")
        }
        
        if let squ: String = values[clubAddrKey] as? String {
            let array: [Substring] = squ.split(separator: "-")
            requestParam.updateValue(array[2], forKey: "area")
            requestParam.updateValue(array[1], forKey: "city")
            requestParam.updateValue(array[0], forKey: "province")
        }
        
        MTClubTool.editClub(provider: provider, requestParam: requestParam, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            if model?.code == 200 {
                
                weakSelf.isEditMode = false
                
                weakSelf.form.removeAll()
                
                weakSelf.setupForm(hiddenGid: false)
                
                weakSelf.parseData(requestParam)
            }
        }) { (error) in
            
        }
    }

    private func parseData(_ requestParam: [String : Any]? = nil) {
        
        setValue(value: group.gid, forTag: "gid")
        
        if let params = requestParam {
            if let remark = params["remark"] as? String {
                setValue(value: remark, forTag: clubDescriptionKey)
            }
            
            if let name = params["name"] as? String {
                setValue(value: name, forTag: clubNameKey)
            }
            
            let p: String = String((params["province"] as! Substring))
            let c: String = String((params["city"] as! Substring))
            let a: String = String((params["area"] as! Substring))
            setValue(value: p + "-" + c + "-" + a, forTag: clubAddrKey)
        } else {
            if let name = group.name {
                setValue(value: name, forTag: clubNameKey)
            }
            setValue(value: "", forTag: clubAddrKey)
            setValue(value: "", forTag: clubDescriptionKey)
            setValue(value: "", forTag: clubMemberKey)
        }
    }
    
    
    /// 编辑俱乐部
    @objc private func editClubInfo() {
        if isEditMode {
            return
        }
        
        self.commitButton.isHidden = false
        
        isEditMode = true
        
        form.removeAll()
        
        setupForm(hiddenGid: true)
        
        parseData()
        
        self.validatorDataDictionary()
        
    }
    
    // MARK: - 检查数据有效性
    private func validatorDataDictionary() {
        
        let validationErrors: [ValidationError] = self.form.validate()
        if validationErrors.count != 0 {
            commitButton.isUserInteractionEnabled = false
            commitButton.backgroundColor = UIColor.redpack.x5d5d5d
            return
        } else {
            commitButton.isUserInteractionEnabled = true
            commitButton.backgroundColor = UIColor.theme.main
        }
    }
    
    /// 赋值
    /// - Parameters:
    ///   - value:
    ///   - tag:
    private func setValue(value: String, forTag tag: String) {
        switch tag {
        case "gid", clubNameKey:
            if let row: MTClubDetailTextRow = self.form.rowBy(tag: tag) as? MTClubDetailTextRow {
                row.cell.contentString = value
                row.value = value
                row.reload()
                row.cellUpdate { (cell, row) in
                    
                    cell.height = { UITableView.automaticDimension }
                }
            }
        case clubAddrKey:
            if let row: MTClubAreaRow = self.form.rowBy(tag: tag) as? MTClubAreaRow {
                if value.count > 0 {
                    row.value = value
                    row.cell.contentString = value
                } else {
                    var area: String = ""
                    if let areaArray = group.desc?.components(separatedBy: groupInfoSeprate), areaArray.count == 4 {
                        area += areaArray[1] + "-"
                        area += areaArray[2] + "-"
                        area += areaArray[3]
                    }
                    row.value = area
                    row.cell.contentString = area
                }
                row.reload()
                row.cellUpdate { (cell, row) in
                    
                    cell.height = { UITableView.automaticDimension }
                }
            }
        case clubDescriptionKey:
            if let row: MTClubDetailTextRow = self.form.rowBy(tag: tag) as? MTClubDetailTextRow {
                if value.count > 0 {
                    row.cell.contentType = .editTextMutiply
                    row.value = value
                    row.cell.contentString = value
                } else {
                    if let areaArray = group.desc?.components(separatedBy: groupInfoSeprate), let desc = areaArray.first {
                        row.cell.contentString = desc
                        row.cell.contentType = .editTextMutiply
                        row.value = desc
                    }
                }
                row.reload()
                row.cellUpdate { (cell, row) in
                    
                    cell.height = { UITableView.automaticDimension }
                }
            }
        case clubMemberKey:
            if let row: MTClubDetailMemberRow = self.form.rowBy(tag: tag) as? MTClubDetailMemberRow {
                if self.group != nil {
                    row.cell.group = self.group
                    row.reload()
                    row.cellUpdate { (cell, row) in
                        
                        cell.height = { UITableView.automaticDimension }
                    }
                }
            }
        default:
            break
        }
    }
    
    private func showValidationMsg(msgs: [ValidationError]) {
        MBProgressHUD_JChat.show(text: msgs.first!.msg, view: self.view)
    }
    
    private func setupForm(hiddenGid: Bool) {
        
        let section = Section()
        form +++ section
        if hiddenGid == false {
            section
            <<< MTClubDetailTextRow(){ row in
                row.cell.tipString = "ID:"
                row.cell.contentString = " "
                row.cell.placeholder = ""
                row.cell.isEditMode = false
                row.disabled = Condition(booleanLiteral: hiddenGid)
                row.add(rule: MTClubNameRule())
                row.tag = "gid"
                row.updateCell()
            }.onChange({ (row) in
                self.validatorDataDictionary()
            })
        }
        section
            <<< MTClubDetailTextRow(){ row in
                row.cell.tipString = "名称"
                row.cell.contentString = " "
                row.cell.placeholder = ""
                row.cell.isEditMode = hiddenGid
                row.disabled = Condition(booleanLiteral: hiddenGid)
                row.add(rule: MTClubNameRule())
                row.tag = clubNameKey
                row.updateCell()
            }.onChange({ (row) in
                self.validatorDataDictionary()
            })
            
            <<< MTClubAreaRow() { row in
                row.cell.tipString = "城市"
                row.cell.contentString = " "
                row.cell.isEditMode = hiddenGid
                row.disabled = Condition(booleanLiteral: hiddenGid)
                row.add(rule: RuleRequired())
                row.tag = clubAddrKey
            }.onChange({ (row) in
                self.validatorDataDictionary()
            })
            
            <<< MTClubDetailTextRow(){ row in
                row.cell.tipString = "俱乐部简介"
                row.cell.contentString = " "
                row.cell.contentType = .editTextMutiply
                row.cell.isEditMode = hiddenGid
                row.tag = clubDescriptionKey
                row.cell.maxTextLength = 50
//                row.add(rule: RuleRequired())
                row.updateCell()
            }.onChange({ (row) in
                self.validatorDataDictionary()
            })
            
            <<< MTClubDetailMemberRow(){ row in
                row.tag = clubMemberKey
                row.cell.delegate = self
                row.hidden = Condition(booleanLiteral: isEditMode)
                row.cell.group = self.group
            }
        
        GroupTableSeparatorFix.removeFirstAndLastSeparatorLine()
    }
    
    @objc private func chat() {
        /// 如果是从聊天界面过来的, 直接pop掉就好
        if comformChat {
            self.navigationController?.popViewController(animated: true)
            return
        }
        JMSGGroup.groupInfo(withGroupId: "\(self.group.gid)", completionHandler: { (result, error) in
            if error == nil, let group = result as? JMSGGroup {
                /// 不是这个组的成员
                group.memberInfoList({ (result, error) in
                    if error == nil {
                        if let userInfos: [JMSGGroupMemberInfo] = result as? [JMSGGroupMemberInfo] {
                            let r : [JMSGUser?] = userInfos.map { (info) -> JMSGUser? in
                                return info.user
                            }
                            /// 判断是否是俱乐部成员
                            if r.contains(JMSGUser.myInfo()) == false {
                                MBProgressHUD_JChat.show(text: "请先加入俱乐部", view: self.view)
                                return
                            }
                            /// 创建群聊会话
                            JMSGConversation.createGroupConversation(withGroupId: "\(self.group.gid)") { [weak self] (conversation, error) in
                                guard let weakSelf = self else { return }
                                if error == nil, conversation != nil {
                                    if let nav = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.viewControllers?[1] as? BaseNavController {
                                        nav.selectCategory()
                                        
                                        DispatchQueue.main.after(0.25) {
                                            let conv: JMSGConversation = conversation as! JMSGConversation
                                            nav.pushViewController(JCChatViewController(conversation: conv), animated: true)
                                        }
                                        
                                        DispatchQueue.main.after(1, execute: {
                                            weakSelf.navigationController?.popToRootViewController(animated: false)
                                        })
                                    }
                                }
                            }
                        }
                    }
                })
            }
        })
    }
    
    lazy var commitButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.layer.cornerRadius = 22
        btn.layer.masksToBounds = true
        btn.setTitle("保存", for: .normal)
        btn.setTitleColor(UIColor.text.x161616, for: .normal)
        btn.backgroundColor = UIColor.redpack.x5d5d5d
        //btn.isUserInteractionEnabled = false
        btn.isHidden = true
        btn.addTarget(self, action: #selector(commitClubInfo), for: .touchUpInside)
        return btn
    }()
    
    lazy var rightEditButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("修改信息", for: .normal)
        btn.addTarget(self, action: #selector(editClubInfo), for: .touchUpInside)
        btn.setTitleColor(UIColor.redpack.x5d5d5d, for: .normal)
        btn.titleLabel?.font = PingFangSCRegularFont(14)
        return btn
    }()
    
    lazy var IMBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("进入聊天", for: .normal)
        btn.addTarget(self, action: #selector(chat), for: .touchUpInside)
        btn.setTitleColor(UIColor.text.x161616, for: .normal)
        btn.backgroundColor = UIColor.theme.main
        btn.titleLabel?.font = PingFangSCMediumFont(14)
        btn.layer.cornerRadius = 10
        btn.layer.masksToBounds = true
        return btn
    }()
}

extension MTClubDetailViewController {
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
}

extension MTClubDetailViewController: MTClubDetailMemberCellDelegate {
    func clickMoreButton(clickButton button: UIButton) {
        let vc = MTMemberViewController(group: self.group)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func clickAddCell() {
        let vc = JCUpdateMemberViewController(updateMemberType: .club) { [weak self] (addUserNames) in
            guard let weakSelf = self else { return }
            weakSelf.users = weakSelf.users + addUserNames
            
            var uns: [String] = []
            for item in addUserNames {
                uns.append(item.username)
            }
            
            /// 新增了成员需要移除本地缓存好的俱乐部头像
            KingfisherManager.shared.cache.removeImage(forKey: weakSelf.group.gid)
            
            let requestParam : [String : Any] = ["id" : weakSelf.group.gid, "type" : 1, "users" : uns]
            
            MTClubTool.operateClubUsers(provider: weakSelf.provider, operateType: .club, requestParam: requestParam, complete: { (model) in
                
            }) { (error) in
                
            }
        }
        vc.group = group
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func clickRemoveCell() {
        let vc = JCRemoveMemberViewController(updateMemberType: .club) { [weak self] (removeUserNames) in
            guard let weakSelf = self else { return }
            
            weakSelf.users.removeAll { (user) -> Bool in
                return removeUserNames.contains { (rmUser) -> Bool in
                    return rmUser.isEqual(to: user)
                }
            }
            
            var uns: [String] = []
            for item in removeUserNames {
                uns.append(item.username)
            }
            
            let requestParam : [String : Any] = ["id" : weakSelf.group.gid, "type" : 2, "users" : uns]
            
            MTClubTool.operateClubUsers(provider: weakSelf.provider, operateType: .club, requestParam: requestParam, complete: { (model) in
                
            }) { (error) in
                
            }
            
        }
        vc.group = group
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
//    func didSelectCell(indexPath: IndexPath) {
//        let index = indexPath.section * 5 + indexPath.row
//        let user = users[index]
////        if user.isEqual(to: JMSGUser.myInfo()) {
////            navigationController?.pushViewController(JCMyInfoViewController(), animated: true)
////            return
////        }
////        let vc = JCUserInfoViewController()
////        vc.user = user
//        let vc = MineViewController(username: user.username)
//        navigationController?.pushViewController(vc, animated: true)
//    }
    
    func didSelectCell(userName: String) {
        let vc = MineViewController(username: userName)
        navigationController?.pushViewController(vc, animated: true)
    }
    
}

extension MTClubDetailViewController {
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .backgroundStyleOpaque, .showShadowImage]
    }
}
